<?php defined('SYSPATH') OR die('No direct access allowed.');

class Model_Cms_Pages extends Model {
	
	public function get_all_pages()
	{
		return DB::Select()->from('pages')
					->order_by('created_at','desc')
					->execute();
	}
	
	public function get_page($id)
	{
		return DB::Select()->from('pages')
					->where('id','=',$id)
					->execute()->current();
	}
	
	public function count_pages()
	{
		$count = DB::select(array('COUNT("*")', 'total_count'))
				->from('pages')
				->execute()->get('total_count');
		return $count;
	}
	
	public function add_page($post)
	{
		$title = Security::xss_clean(trim($_POST['title']));
		$content = $_POST['editor'];
		$content_stripped = Pages::striptags($_POST['editor']);
		$short = $_POST['editor_1'];
		$short_stripped = Pages::striptags($_POST['editor_1']);
		$description = trim($_POST['seo_description']);
		$keywords = trim($_POST['seo_keywords']);
		$cat_id = (int)trim($_POST['cat_check']);
		if(isset($_POST['publish']))
				$published = 1;
				else $published = 0;
		
		DB::insert('pages', array('title','content','content_stripped','short','short_stripped','category_id','published','seo_description','seo_keywords','created_at'))
			->values(array($title,$content,$content_stripped,$short,$short_stripped,$cat_id,$published,$description,$keywords,time()))
			->execute();
		return $cat_id;
	}
	
	public function del_page($id)
	{
		DB::delete('pages')->where('id','=',$id)->execute();
	}
	
	public function update_page($id,$post)
	{
		$title = Security::xss_clean(trim($_POST['title']));
		$content = $_POST['editor'];
		$content_stripped = Pages::striptags($_POST['editor']);
		$description = trim($_POST['seo_description']);
		$keywords = trim($_POST['seo_keywords']);
		if($id == 12 || $id == 13 || $id == 14) // ukrywanie skrótu przy statycznych/informacyjnych
		{
			$short = "";
			$short_stripped = "";
		}else{
			$short = $_POST['editor_1'];
			$short_stripped = Pages::striptags($_POST['editor_1']);
		}
		if(isset($_POST['publish']))
				$published = 1;
				else $published = 0;
		
		DB::update('pages')
			->set(array('title'=>$title,'content'=>$content,'content_stripped'=>$content_stripped,'short'=>$short,'short_stripped'=>$short_stripped,'published'=>$published,'seo_description'=>$description,'seo_keywords'=>$keywords,'updated_at'=>time()))
			->where('id','=',$id)->execute();
	}
	
	public function save_excerpt_photo($id,$file)
	{
		DB::update('pages')
			->set(array('excerpt_photo'=>$file))
			->where('id','=',$id)->execute();
	}
	
	public function get_all_categories()
	{
		return DB::Select()->from('pages')
					->where('category','=',1)
					->execute();
	}
	
	public function get_category_pages($id)
	{
		return DB::Select()->from('pages')
					->where('category_id','=',$id)
					->order_by('created_at','desc')
					->execute();
	}
}
?>